package com.raymond.cmpp.client.netty;

import cn.hutool.core.lang.Assert;
import com.raymond.cmpp.client.CmppClient;
import com.raymond.cmpp.client.handler.*;
import com.raymond.cmpp.common.codec.AgreementDecoder;
import com.raymond.cmpp.common.netty.MsgDecoder;
import com.raymond.cmpp.common.netty.MsgEncoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;


/**
 * 客户端初始化handler
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2021-08-06 11:39
 */
public class ClientHandlersInitializer extends ChannelInitializer<SocketChannel> {

    private ReconnectHandler reconnectHandler;

    private CmppClient cmppClient;

    public ClientHandlersInitializer(CmppClient cmppClient) {
        Assert.notNull(cmppClient, "QueueClient can not be null.");
        this.reconnectHandler = new ReconnectHandler(cmppClient);
        this.cmppClient = cmppClient;
    }


    @Override
    protected void initChannel(SocketChannel ch) {

        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new IdleStateHandler(0, 0, 10));
        pipeline.addLast(new LengthFieldBasedFrameDecoder(10 * 1024 , 0, 4, -4, 0, true));
        pipeline.addLast(new AgreementDecoder());
        pipeline.addLast(new MsgDecoder());
        pipeline.addLast(new MsgEncoder());
        pipeline.addLast(new SubmitResponseMessageHandler(cmppClient));
        pipeline.addLast(new DeliverRequestMessageHandler());
        pipeline.addLast(new ConnectResponseMessageHandler(cmppClient));
        pipeline.addLast(new TerminateResponseMessageHandler(cmppClient));
        pipeline.addLast(new ActiveTestResponseMessageHandler());
        pipeline.addLast(new ClientIdleStateTrigger());
        pipeline.addLast(this.reconnectHandler);
    }
}
